# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db.models import *
from django.shortcuts import render
from rest_framework import permissions
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.authentication import SessionAuthentication
from rest_framework_extensions.cache.mixins import CacheResponseMixin
from rest_framework.response import Response
from rest_framework import status
from rest_framework import mixins, viewsets
from rest_framework_extensions.cache.mixins import CacheResponseMixin
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated
from django.forms.models import model_to_dict 
#from rest_framework.views import APIView
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
import time
from datetime import datetime
from models import *
from serializer import *
from filters import * 
from image_handle import DrawSomething 
import sys
reload(sys) 
sys.setdefaultencoding('utf8')

class customerPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'page_size'
    page_query_param = "page"
    max_page_size = 100

class TestViewSet(mixins.UpdateModelMixin, mixins.ListModelMixin,mixins.RetrieveModelMixin, viewsets.GenericViewSet):
        serializer_class = UserInfoSerializer
	def get_queryset(self):
	    #GenericAPIView 子类查询集的最简单方法是重写get_queryset()方法。
	    user = self.request.user
	    return UserInfo.objects.all()

class MachantLoginViewSet(mixins.ListModelMixin,mixins.RetrieveModelMixin, viewsets.GenericViewSet):
        filter_class  = merchantselfFilter
	filter_backends = (DjangoFilterBackend,)

	def get_queryset(self):
	    return merchant_info.objects.all()
	def get_serializer_class(self):
            return merchantselfSerializer
        def list(self, request, *args, **kwargs):
	    queryset = self.filter_queryset(self.get_queryset())
	    try:
	        queryset = queryset.filter(mobile=request.GET["mobile"],password=request.GET["password"] )
            except Exception,e:
	        queryset = []
	    serializer = self.get_serializer(queryset, many=True)
	    return Response(serializer.data)

class VodErrorLogViewSet(mixins.UpdateModelMixin, mixins.ListModelMixin, mixins.DestroyModelMixin, mixins.CreateModelMixin,mixins.RetrieveModelMixin, viewsets.GenericViewSet):
        filter_class  = VodErrorLogFilter
	filter_backends = (DjangoFilterBackend,)
        pagination_class = customerPagination
	def get_queryset(self):
	    return Vod_errorlog.objects.all()
	def get_serializer_class(self):
            return VodErrorLogSerializer

	def list(self,request,*args,**kwargs):
	    queryset = self.filter_queryset(self.get_queryset())
	    page = self.paginate_queryset(queryset)
	    if page is not None and 'page' in request.GET.keys():
	        serializer = self.get_serializer(page, many=True)
		return self.get_paginated_response(serializer.data)
	    serializer = self.get_serializer(queryset, many=True)
	    serializer.is_valid(raise_exception=True)
            self.perform_create(serializer)
            headers = self.get_success_headers(serializer.data)
        ''' 
        def create(self,request,*args,**kwargs):
	    mutable_requestData = request.data.copy()
	    print 'Vod error log :'
	    print mutable_requestData
	    #mutable_requestData.update({'merchantid':3})
	    serializer = self.get_serializer(data=request.data)
	    serializer.is_valid(raise_exception=True)
            self.perform_create(serializer)
            headers = self.get_success_headers(serializer.data)
	    return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
	 '''
#web使用用户信息
class UserinfoViewSet(mixins.UpdateModelMixin, mixins.ListModelMixin,mixins.RetrieveModelMixin, viewsets.GenericViewSet):
	pagination_class = customerPagination
	filter_backends = ( filters.SearchFilter,)
	search_fields = ['NickName']
	def get_queryset(self):
	    return UserInfo.objects.all().order_by('-LastLoginTime')
	def get_serializer_class(self):
            return UserInfoSerializer
	def list(self,request,*args,**kwargs):
	    queryset = self.filter_queryset(self.get_queryset())
	    page = self.paginate_queryset(queryset)
	    if page is not None and 'page' in request.GET.keys():
	        serializer = self.get_serializer(page, many=True)
		return self.get_paginated_response(serializer.data)
	    serializer = self.get_serializer(queryset, many=True)
	    return Response(serializer.data)

#web使用查询订单购物车
class ProductOrderViewSet(mixins.UpdateModelMixin, mixins.ListModelMixin,mixins.RetrieveModelMixin, viewsets.GenericViewSet):
	'''
	list 查询
	create 创建
	delete 删除
	put 修改
	'''
	pagination_class = customerPagination
	filter_backends = (DjangoFilterBackend,)	     
        filter_class  = productOrderFilter 
	def get_queryset(self):
	    return product_order.objects.all()
	def get_serializer_class(self):
            return productOrderSerializer
	def list(self,request,*args,**kwargs):
	    queryset = self.filter_queryset(self.get_queryset())
	    page = self.paginate_queryset(queryset)
	    if page is not None and 'page' in request.GET.keys():
	        serializer = self.get_serializer(page, many=True)
		return self.get_paginated_response(serializer.data)
	    serializer = self.get_serializer(queryset, many=True)
	    return Response(serializer.data)

class MachineActiveStatusViewSet(mixins.UpdateModelMixin, mixins.ListModelMixin,mixins.RetrieveModelMixin, viewsets.GenericViewSet):
        #pagination_class = customerPagination
        
	def get_queryset(self):
	    print self.request.GET
	    return MachineInfo.objects.all()
	def get_serializer_class(self):
	    return MachineActiveStatusSerializer
#web使用查询机器信息 app使用修改激活状态
class machineinfoViewSet(mixins.UpdateModelMixin, mixins.ListModelMixin, mixins.DestroyModelMixin, mixins.CreateModelMixin,
                     mixins.RetrieveModelMixin, viewsets.GenericViewSet):
        pagination_class = customerPagination
	def get_queryset(self):
	    return MachineInfo.objects.all()
	def get_serializer_class(self):
	    return  machineinfoSerializer
	def list(self,request,*args,**kwargs):
	    queryset = self.filter_queryset(self.get_queryset())
	    page = self.paginate_queryset(queryset)
	    if page is not None and 'page' in request.GET.keys():
	        serializer = self.get_serializer(page, many=True)
		return self.get_paginated_response(serializer.data)
	    serializer = self.get_serializer(queryset, many=True)
	    return Response(serializer.data)
	def partial_update(self, request, *args, **kwargs):
	    instance = self.get_object()
	    if 'STATUS' in request.data.keys(): 
	    
	        if "merchantid" not in request.data.keys() or "mid" not in request.data.keys():
		    
	            return Response({'info_code':10001,'info_detail':"merchantid mid"})
	        result = machine_relation.objects.filter(mid=request.data["mid"],merchantid=request.data["merchantid"])
                if not result:
	            return Response({'info_code':10002,'info_detail':"merchantid does not match"})
		else:
		    instance.STATUS = request.data["STATUS"]
	            instance.ACTIVE_TIME = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())) 
		    result = store_info.objects.get(merchantid=request.data["merchantid"],is_defaultgroup=1)
		    default_storeid = result.storeid

                    machine_relation.objects.filter(mid=request.data["mid"]).update(storeid=default_storeid)
	            instance.save()
                    import requests
		    url  = "http://14.119.109.232:8085/MidActivate"
		    data = {"mid":request.data["mid"]} 
		    try:
		        response = requests.post(url,data=data,timeout=2)
                    except Exception,e:
		        print e

	    return self.update(request, *args, **kwargs)	

        def create(self,request,*args,**kwargs):
	    nowtime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))
	    #更新时间 
	    mutable_requestData = request.data.copy()
	    #暂时将创建的机器商户归属全部为3
	    mutable_requestData.update({'merchantid':3})
            #if  self.request.user !="admin" or not request.data.has_key("merchantid") :
            #    return Response('merchantid')
	    #注册机器成功 添加绑定机器与商户
	    serializer = self.get_serializer(data=request.data)
	    serializer.is_valid(raise_exception=True)
            self.perform_create(serializer)
            headers = self.get_success_headers(serializer.data)
            #找到该商户的未分组店id
	    result = store_info.objects.get(is_defaultgroup=1,merchantid=mutable_requestData["merchantid"])
	    machine_relation.objects.create(merchantid=mutable_requestData["merchantid"],storeid=result.storeid,mid=serializer.data["MachineId"],updatetime=nowtime)
	    return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)


#app修改门店信息
class storeinfoViewSet(mixins.UpdateModelMixin, mixins.ListModelMixin, mixins.DestroyModelMixin, mixins.CreateModelMixin,mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    
	def get_queryset(self):
	    return store_info.objects.all()
	def get_serializer_class(self):
	    return  storeinfoSerializer

#web使用查询商户信息
class merchantinfoViewSet(mixins.UpdateModelMixin, mixins.ListModelMixin, mixins.DestroyModelMixin, mixins.CreateModelMixin,
                     mixins.RetrieveModelMixin, viewsets.GenericViewSet):
        pagination_class = customerPagination	
	filter_backends = (DjangoFilterBackend, filters.SearchFilter,)
        filter_class  = merchantinfoFilter 
	search_fields = ['merchantname']
	def get_queryset(self):
	    return merchant_info.objects.all()
	def get_serializer_class(self):
	    return  merchantinfoSerializer
        def create(self,request,*args,**kwargs):
	    nowtime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))
	    #更新时间 
	    q = request.data.copy()
	    q.update({'updatetime':nowtime})
	    #注册商户 添加默认未分组店面
	    serializer = self.get_serializer(data=q)
	    serializer.is_valid(raise_exception=True)
            self.perform_create(serializer)
            headers = self.get_success_headers(serializer.data)
	    store_info.objects.create(merchantid=serializer.data["merchantid"],storename="未分组",is_defaultgroup=1)

	    return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
	def list(self,request,*args,**kwargs):
	    queryset = self.filter_queryset(self.get_queryset())
	    page = self.paginate_queryset(queryset)
	    if page is not None and 'page' in request.GET.keys():
	        serializer = self.get_serializer(page, many=True)
		return self.get_paginated_response(serializer.data)
	    serializer = self.get_serializer(queryset, many=True)
	    return Response(serializer.data)

#web使用查询用户消费信息
class userconsumeViewSet(mixins.UpdateModelMixin, mixins.ListModelMixin,mixins.CreateModelMixin,mixins.RetrieveModelMixin, viewsets.GenericViewSet):
        pagination_class = customerPagination
	filter_backends = (DjangoFilterBackend,)	     
        filter_class  = userconsumeFilter 
	#search_fields = ('pay_time',)
	def list(self,request,*args,**kwargs):
	    queryset = self.filter_queryset(self.get_queryset())
            total_mount = user_consume.objects.values('mount').filter(status=2).aggregate(Sum('mount'))["mount__sum"]
	    page = self.paginate_queryset(queryset)
	    if page is not None and 'page' in request.GET.keys():
	        serializer = self.get_serializer(page, many=True)
	        result = {'total_mount':total_mount,'result':serializer.data}
		return self.get_paginated_response(result)
	    serializer = self.get_serializer(queryset, many=True)
	    result = {'total_mount':total_mount,'result':serializer.data}
	    return Response(result)
	def get_queryset(self):
	    for row in user_consume.objects.exclude(uid=0):
	        print row.uid
	    return user_consume.objects.exclude(uid=0)
	def get_serializer_class(self):
	    print '1___________23'
	    return  userconsumeSerializer

#web使用查询用户充值信息
class userrechargeViewSet(mixins.UpdateModelMixin, mixins.ListModelMixin,mixins.CreateModelMixin,mixins.RetrieveModelMixin, viewsets.GenericViewSet):
        pagination_class = customerPagination	
	filter_backends = (DjangoFilterBackend,)	     
        filter_class  = userrechargeFilter 
	#search_fields = ('pay_time',)
	def list(self,request,*args,**kwargs):
	    queryset = self.filter_queryset(self.get_queryset())
            total_mount = user_recharge.objects.values('mount').filter(recharge_status=1).aggregate(Sum('mount'))["mount__sum"]
	    print '2__________2'
	    print total_mount
	    page = self.paginate_queryset(queryset)
	    if page is not None and 'page' in request.GET.keys():
	        serializer = self.get_serializer(page, many=True)
	        result = {'total_mount':total_mount,'result':serializer.data}
		return self.get_paginated_response(result)
	    serializer = self.get_serializer(queryset, many=True)
	    result = {'total_mount':total_mount,'result':serializer.data}
	    return Response(result)

	def get_queryset(self):
	    return user_recharge.objects.exclude(uid=0)
	def get_serializer_class(self):
	    return  userrechargeSerializer

#机器消费流水
class machinedetailconsumeViewSet(mixins.UpdateModelMixin, mixins.ListModelMixin, mixins.DestroyModelMixin, mixins.CreateModelMixin,
                     mixins.RetrieveModelMixin, viewsets.GenericViewSet):
	'''根据机器筛选机器流水收入'''	     
	filter_backends = (DjangoFilterBackend,)	     
        filter_class  = userconsumeFilter 
	search_fields = ('pay_time',)
	def get_queryset(self):
	    return user_consume.objects.all().exclude(uid=0)
	def get_serializer_class(self):
	    return  userconsumeSerializer
        
        def list(self, request, *args, **kwargs): 
	    queryset = self.filter_queryset(self.get_queryset())
	    queryset = queryset.filter(mid=request.GET["mid"])
	    serializer = self.get_serializer(queryset, many=True)
            return Response(serializer.data)

#门店消费	    
class StoreReportViewSet(mixins.UpdateModelMixin, mixins.ListModelMixin, mixins.DestroyModelMixin, mixins.CreateModelMixin,
                     mixins.RetrieveModelMixin, viewsets.GenericViewSet):
        
        filter_backends = (DjangoFilterBackend,)
        filter_class  = StoreReportFilter 

	def get_queryset(self):
	    return store_report.objects.all()
	def get_serializer_class(self):
	    return  StoreReportSerializer
        def list(self, request, *args, **kwargs): 
	    #门店收入
	    queryset = self.filter_queryset(self.get_queryset())
	    try:
	        store_queryset = machine_relation.objects.filter(merchantid=request.GET["merchantid"])
	    except Exception,e:
	        ret = {"status":0,"errinfo":"merchantid is the necessary parameter"}
	        return Response(ret)
	        #serializer = self.get_serializer(queryset, many=True)
		#return Response(serializer.data)

            #门店与机器关系字典
	    store_mids_dic = {}
	    #返回结果字典
	    resultdic = {}
            for row in store_queryset:
	        if str(row.storeid) not in store_mids_dic:
	            store_mids_dic[str(row.storeid)] = []
	        store_mids_dic[str(row.storeid)].append(row.mid)
            #属于商户的门店		
            queryset = queryset.filter(storeid__in=store_mids_dic.keys())
            for row in queryset :
	        date = row.datetime
	        year,month,day = str(date.year),str(date.month),str(date.day)
		store_detail= store_info.objects.get(storeid=row.storeid)

                if year not in resultdic:
	            resultdic[year] ={}

	        if month not in resultdic[year]:
                    resultdic[year][month] = {'days':{},"mouth_income":0}
                resultdic[year][month]["mouth_income"] = resultdic[year][month]["mouth_income"]+row.all_income
                try:
		    #上传参数mouth 只查询每月收入。
	            m = request.GET["mouth"]

		    continue

		except Exception,e:
		    pass
                if day not in resultdic[year][month]['days']:
                    resultdic[year][month]['days'][day] = {}
		    resultdic[year][month]['days'][day]["all_income"] = 0
                    resultdic[year][month]['days'][day]["store"] = {}
		mids = []
                for machineid in store_mids_dic[str(store_detail.storeid)]: 
		    try: 
		        mid_income_queryset = machine_report.objects.get(mid=machineid,datetime=date)
                        mid_income =  mid_income_queryset.all_income
		        mid_info_queryset = MachineInfo.objects.get(MachineId=machineid)
                   
                        machine_name = mid_info_queryset.MACHINE_NAME
                        _= {'mid':machineid,'mid_income':mid_income,'machine_name':machine_name}
		        mids.append(_)
                    except Exception,e:
		        pass
                resultdic[year][month]['days'][day]["all_income"] =resultdic[year][month]['days'][day]["all_income"] + row.all_income
                resultdic[year][month]['days'][day]["store"][str(store_detail.storeid)] = {
		'storename':store_detail.storename,
                "storeid"  :store_detail.storeid,
                "income":store_detail.all_income,
		"is_defaultgroup":store_detail.is_defaultgroup,
		"mids":mids
		}

            ret = {'status':1,'result':resultdic}
            return Response(ret)
